#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

int main()
{
    pid_t pid = fork();
    if(pid < 0)
    {
        perror("fork() fail");
        exit(1);
    }
    //子进程
    if(pid == 0)
    {
        printf("i am child process\n");
        sleep(5);
        exit(40);
    }
    //父进程代码块
    else
    {
        int status;
        pid_t child_pit = waitpid(pid,&status,0); //阻塞等待子进程
        
        if(child_pit == -1)
        {
            perror("waitpid fail");
            exit(1);
        }

        printf("\nchild pid: %d:\n",child_pit);
        //分析退出状态
        if(WIFEXITED(status))//检查是否正常退出
        {
            printf("退出码：%d\n",WEXITSTATUS(status));
        }
        else
        {
            printf("N/A,进程被信号中止/进程接收到信号而退出\n");
        }
        
        if(WIFSIGNALED(status)) //检查是否被信号终止
        {
            printf("WTERMSIG(status)"); //打印终止信号
            printf("core dump: %s\n", WCOREDUMP(status) ? "Yes" : "No");
        }
        else
        {
            printf("终止信号：无，core dump：无\n");
        }

        if(WIFSTOPPED(status)) //检查是否被信号停止
        {
            printf("停止信号：%d\n",WSTOPSIG(status));
        }       
        else
        {
            printf("未被信号停止——无停止信号\n");
        }
                        
    }

    return 0;
}

